<template>
  <view class="container">
    <!-- 定义一个 canvas 组件作为签字画布 -->
    <canvas class="canvas" canvas-id="signCanvas" :width="canvasWidth" :height="canvasHeight" :style="canvasStyle" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas>
    <view class="btn-group">
      <!-- 添加清除和保存按钮 -->
      <button @click="clearCanvas">清除</button>
      <button @click="saveSignature">保存</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      context: null, // 画布绘图上下文
      isDrawing: false, // 标记是否正在绘制
      lastPoint: { x: 0, y: 0 }, // 上一个触摸点的位置
      canvasWidth: 500, // 画布宽度
      canvasHeight: 300, // 画布高度
      canvasStyle: 'position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);' // 画布位置样式
    }
  },
  onLoad() {
    // 在组件加载时获取画布绘图上下文
    this.context = uni.createCanvasContext('signCanvas', this)
  },
  methods: {
    touchStart(e) {
      // 在触摸开始时设置绘制标记并保存触摸点位置
      this.isDrawing = true
      this.lastPoint = { x: e.touches[0].x, y: e.touches[0].y }
    },
    touchMove(e) {
      // 在触摸移动时,如果正在绘制,则连续绘制线段
      if (this.isDrawing) {
        this.context.beginPath()
        this.context.moveTo(this.lastPoint.x, this.lastPoint.y)
        this.context.lineTo(e.touches[0].x, e.touches[0].y)
        this.context.stroke()
        this.lastPoint = { x: e.touches[0].x, y: e.touches[0].y }
      }
    },
    touchEnd() {
      // 在触摸结束时,设置绘制标记为 false 并更新画布
      this.isDrawing = false
      this.context.draw()
    },
    clearCanvas() {
      // 清除画布内容
      this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
      this.context.draw()
    },
    saveSignature() {
      // 保存签名图片
      this.context.draw(true, () => {
        uni.canvasToTempFilePath({
          canvasId: 'signCanvas',
          success: (res) => {
            // 这里可以上传图片或进行其他操作
            console.log(res.tempFilePath)
          }
        }, this)
      })
    }
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  position: relative;
}
.canvas {
  border: 1px solid #ccc;
}
.btn-group {
  margin-top: 20px;
}
</style>